package com.shiwaixiangcun.authz.web.context;

import com.shiwaixiangcun.core.shiro.AuthzUtils;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author SilentWu
 */
public class OAuthShiroHandlerExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        handleUnauthorizedException(response, ex);
        return null;
    }

    private void handleUnauthorizedException(HttpServletResponse response, Exception ex) {
        OAuthResponse oAuthResponse;
        try {
            oAuthResponse = OAuthASResponse.errorResponse(403)
                    .setError(OAuthError.ResourceResponse.INVALID_TOKEN)
                    .setErrorDescription(ex.getMessage())
                    .buildJSONMessage();
        } catch (OAuthSystemException e) {
            throw new IllegalStateException(e);
        }

        AuthzUtils.writeOAuthJsonResponse(response, oAuthResponse);
    }

}
